<?php

class App
{
// Здесь храним обьект приложения.
  protected static $application = null;
  
// ***
  protected $dsn = '';
  protected $dbuser = '';
  protected $dbpassw = '';
  
  public $basePath = '';
  public $baseURL = '';
  
  public $tpl = null;
  public $viewPath = '';

  public $defController = '';
  public $defAction = '';
  
  public $php_time_zone = 'Europe/Kiev';
  public $time_zone_offset = '+2:00';
  
  function __construct() {
  
// ***
	self::$application = $this;
	
	$this->basePath = substr(dirname(__FILE__), 0, strrpos(dirname(__FILE__), DIRECTORY_SEPARATOR) );
    $this->baseUrl = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
	
// Подготовка Smarty
	require_once( $this->basePath . DIRECTORY_SEPARATOR .'lib'. DIRECTORY_SEPARATOR .'Smarty'.
			DIRECTORY_SEPARATOR .'libs'. DIRECTORY_SEPARATOR .'Smarty.class.php' );

	$tpl = new Smarty;
	$tpl->setCacheDir($this->basePath. DIRECTORY_SEPARATOR .'data'. DIRECTORY_SEPARATOR .'cache');
	$tpl->setCompileDir($this->basePath. DIRECTORY_SEPARATOR .'data'. DIRECTORY_SEPARATOR .'templates_c');
	$tpl->setConfigDir($this->basePath. DIRECTORY_SEPARATOR .'configs');
		
	$this->viewPath = $this->basePath. DIRECTORY_SEPARATOR .'_view';		
	$tpl->setTemplateDir($this->viewPath. DIRECTORY_SEPARATOR .'layout');

	$this->tpl = $tpl;

// Загружанм конфиг. файл
	$tpl->configLoad('matvei.conf');

//  Переменные временной зоны
	$a = $tpl->getConfigVars('php_time_zone');
	if( $a ) $this->php_time_zone = $a;
	
	$a = $tpl->getConfigVars('time_zone_offset');
	if( $a ) $this->time_zone_offset = $a;
	
// Атрибуты базы данных
	$conf_dsn = $tpl->getConfigVars('dsn');
	if( $conf_dsn == 'sqlite:' )
		$this->dsn = 'sqlite:'.$this->basePath. DIRECTORY_SEPARATOR .'data'. DIRECTORY_SEPARATOR .'sqlite.db';
	else 
		$this->dsn = $conf_dsn;
	
	$this->dbuser = $tpl->getConfigVars('username');
	$this->dbpassw = $tpl->getConfigVars('password');

// Default Controller & action
	$this->defController = "login";
	$this->defAction = "index";
  }
  
// ***
  public static function me() {
	return self::$application;
  }

  public static function check_session() {
	if( isset($_SESSION['user_id']) && $_SESSION['user_id'] != '' )
		return true;
		
	if( Tools::isAjax() ) {
		echo json_encode( array('errcode'=>1, 'errmess'=>'Время вашей сессии истекло. Выполните вход в систему.') );
	}
	else {
		header( 'Location: '.Tools::getBaseUrl() );
	}	
	return false;		
  }

  public function js_load( $scr ) {
		session_start();
		echo '<script type="text/javascript">';
		if( !isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0 ) {
			echo "app.alert('AlertDlg', 'Внимание', ".
				"'Извините. Ваше время закончилось по таймауту. Пожалуйста, перерегистрируйтесь.', 'app-icon-stop32');";
		}
		else
			readfile($this->basePath. DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $scr);
		echo '</script>';
  }
  
  public function dbOpen() {
	$pdo = new PDO($this->dsn, $this->dbuser, $this->dbpassw);
	$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$pdo->exec('SET CHARACTER SET utf8');
	$pdo->exec("SET time_zone = '".$this->time_zone_offset."'");
	return $pdo;
  }
  
  public function run() {
  
	date_default_timezone_set($this->php_time_zone);
	
	$controller = $this->defController;
	$action = $this->defAction;
	
	while ( true ) {
		if( !isset($_REQUEST['q']) ) break;
		$req = trim(strip_tags($_REQUEST['q']));
		if( $req === '' ) break;
		
		$qval = explode('/', $req );
		
		if( count( $qval ) > 1 ) {
			$controller = ($qval[0] === '') ? $this->defController : $qval[0];
			$action = ($qval[1] === '') ? $this->defAction : $qval[1];
		}
		else {
			$controller = $qval[0];
		}			
		break;
	}
	
	$model = $controller;
	$controller .= "Controller";

	$controllerFile = $this->basePath. DIRECTORY_SEPARATOR .'_controller'. DIRECTORY_SEPARATOR .$controller.'.php';
	$modelFile = $this->basePath. DIRECTORY_SEPARATOR .'_model'. DIRECTORY_SEPARATOR .$model.'.php';

	require_once( $controllerFile );
	require_once( $modelFile );

// И запускаем приложение
	$cnt = new $controller;
	$cnt->$action();
  }
  
}
?>